package com.djl.seckilldemo.rabbitmq;

import com.alibaba.fastjson.JSON;
import com.djl.seckilldemo.pojo.SeckillMessage;
import com.djl.seckilldemo.pojo.SeckillOrder;
import com.djl.seckilldemo.pojo.User;
import com.djl.seckilldemo.service.IGoodsService;
import com.djl.seckilldemo.service.IOrderService;
import com.djl.seckilldemo.vo.GoodsVo;
import com.djl.seckilldemo.vo.RespBean;
import com.djl.seckilldemo.vo.RespBeanEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @program: seckill-demo
 * @description: 消费者,监听并进行下单操作
 * @author: Mr.dai
 * @create: 2021-10-27 09:53
 **/
@Service
@Slf4j
public class MQReceiver {
    @Autowired
    private IGoodsService  goodsService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IOrderService orderService;
    @RabbitListener(queues = "seckillQueue")
    public void receive(String message){
        log.info("接收到的消息："+message);
        SeckillMessage seckillMessage = JSON.parseObject(message, SeckillMessage.class);
        User user = seckillMessage.getUser();
        Long goodId = seckillMessage.getGoodId();
        GoodsVo goodsVo = goodsService.findGoodsVoByGoodsId(goodId);
        if (goodsVo.getSeckillCount()<1){
                return;
        }
        //判断是否重复抢购
        SeckillOrder seckillOrder = (SeckillOrder)redisTemplate.opsForValue().get("order:" + user.getId() + ":" + goodId);
        if (seckillOrder!=null){
            return;
        }
        orderService.seckill(user,goodsVo);



    }
}
